package top.tsyz.filter;

import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

@Component
@Order(1)
public class RequestLogFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        
        String uri = httpRequest.getRequestURI();
        String method = httpRequest.getMethod();
        String clientIP = getClientIP(httpRequest);
        
        System.out.println("RequestLogFilter - " + method + " " + uri + " from " + clientIP + " at " + new Date());
        
        long startTime = System.currentTimeMillis();
        chain.doFilter(request, response);
        long executeTime = System.currentTimeMillis() - startTime;
        
        System.out.println("RequestLogFilter - " + method + " " + uri + " completed with status " + 
                          httpResponse.getStatus() + " in " + executeTime + "ms");
    }
    
    private String getClientIP(HttpServletRequest request) {
        String xfHeader = request.getHeader("X-Forwarded-For");
        if (xfHeader == null) {
            return request.getRemoteAddr();
        }
        return xfHeader.split(",")[0];
    }
}
